import tkinter as tk
from tkinter import ttk, messagebox
from alg import Solution


class PermutationApp:
    def __init__(self, root):
        self.root = root
        self.root.title("优美排列计算器")
        self.root.geometry("400x320")
        self.root.resizable(False, False)
        
        # 主框架
        main_frame = ttk.Frame(root, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        ttk.Label(main_frame, text="优美排列计算器", font=("Arial", 16, "bold")).pack(pady=(0, 20))
        
        # 输入框
        input_frame = ttk.Frame(main_frame)
        input_frame.pack(fill=tk.X, pady=10)
        
        ttk.Label(input_frame, text="输入n (1-15):").pack(side=tk.LEFT, padx=(0, 10))
        
        self.n_var = tk.StringVar()
        n_entry = ttk.Entry(input_frame, textvariable=self.n_var, width=5)
        n_entry.pack(side=tk.LEFT)
        n_entry.focus()
        
        # 按钮
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(fill=tk.X, pady=20)
        
        ttk.Button(btn_frame, text="计算", command=self.calculate).pack(side=tk.LEFT, padx=10)
        ttk.Button(btn_frame, text="清空", command=self.clear).pack(side=tk.LEFT)
        
        # 结果显示
        ttk.Label(main_frame, text="结果:").pack(anchor=tk.W, pady=(10, 5))
        
        self.result_text = tk.Text(main_frame, height=5, width=40, wrap=tk.WORD)
        self.result_text.pack(fill=tk.BOTH, expand=True)
        
        scrollbar = ttk.Scrollbar(self.result_text, command=self.result_text.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.result_text.config(yscrollcommand=scrollbar.set)
        
        # 状态栏
        self.status_var = tk.StringVar()
        self.status_var.set("就绪")
        ttk.Label(root, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W).pack(side=tk.BOTTOM, fill=tk.X)
        
        self.solution = Solution()
        
    def calculate(self):
        try:
            n = int(self.n_var.get())
            if n < 1 or n > 15:
                messagebox.showerror("输入错误", "请输入1到15之间的整数")
                return
                
            self.status_var.set("计算中...")
            self.root.update()
            
            count = self.solution.countArrangement(n)
            
            self.result_text.delete(1.0, tk.END)
            self.result_text.insert(tk.END, f"当n={n}时，优美排列的数量为：{count}\n")
            
            self.status_var.set("计算完成")
        except ValueError:
            messagebox.showerror("输入错误", "请输入有效的整数")
            self.status_var.set("就绪")
    
    def clear(self):
        self.n_var.set("")
        self.result_text.delete(1.0, tk.END)
        self.status_var.set("就绪")

if __name__ == "__main__":
    root = tk.Tk()
    app = PermutationApp(root)
    root.mainloop()    
